﻿using OMR.EasyBackup.Core.BackupManagers.SQL;
using OMR.EasyBackup.Core.BackupManagers.SQL.EF;
using System;
using System.Linq;

namespace OMR.EasyBackup.Core.BackupManagers
{
    public class SqlServerBackupManager : IBackupManager
    {
        private FileRepoDbEntities db;

        public SqlServerBackupManager()
        {
            db = new FileRepoDbEntities();
        }

        public void Create(Guid userId, string fullpath, byte[] content)
        {
            var file = new tblFile();
            //file.ContentType = File
            file.Id = Guid.NewGuid();
            file.IsDeleted = false;
            file.Path = fullpath;
            file.UserId = userId;

            db.tblFile.Add(file);

            var fileVersion = new tblFileVersion();
            fileVersion.Id = Guid.NewGuid();
            fileVersion.FileId = file.Id;
            fileVersion.FileContent = content;

            file.tblFileVersion.Add(fileVersion);

            db.SaveChanges();
        }

        public void Delete(Guid userId, string fullPath)
        {
            var tmpFile = db.tblFile.FirstOrDefault(f => f.Path == fullPath && f.UserId == userId);

            if (tmpFile != null)
            {
                tmpFile.IsDeleted = true;
                db.SaveChanges();
            }
        }

        public void Rename(Guid userId, string fullPath, string newFullPath)
        {
            var tmpFile = db.tblFile.FirstOrDefault(f => f.Path == fullPath && f.UserId == userId && f.IsDeleted == false);

            if (tmpFile != null)
            {
                tmpFile.Path = newFullPath;
                db.SaveChanges();
            }
        }

        public void Update(Guid userId, string fullPath, byte[] content)
        {
            var tmpFile = db.tblFile.FirstOrDefault(f => f.Path == fullPath && f.UserId == userId && f.IsDeleted == false);

            if (tmpFile == null) // create
            {
                Create(userId, fullPath, content);
            }
            else // update
            {
                var fileVersion = new tblFileVersion();

                fileVersion.Id = Guid.NewGuid();
                fileVersion.FileId = tmpFile.Id;
                fileVersion.FileContent = content;

                tmpFile.tblFileVersion.Add(fileVersion);

                db.SaveChanges();
            }

        }

    }
}
